{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "492f050f-3dc3-44fa-8fdc-03362afd5488",
   "metadata": {},
   "source": [
    "# Reflection\n",
    "\n",
    "\n",
    "In the context of LLM agent building, reflection refers to the process of prompting an LLM to observe its past steps (along with potential observations from tools/the environment) to assess the quality of the chosen actions.\n",
    "This is then used downstream for things like re-planning, search, or evaluation.\n",
    "\n",
    "![Reflection](./img/reflection.png)\n",
    "\n",
    "This notebook demonstrates a very simple form of reflection in LangGraph."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ef94e7e-c9a5-4eee-a865-acf411b5c235",
   "metadata": {},
   "source": [
    "#### Prerequisites\n",
    "\n",
    "We will be using a basic agent with a search tool here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8b323f43-328b-4b4b-88b0-6c84dc0a1d60",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install -U --quiet  langgraph langchain-fireworks\n",
    "%pip install -U --quiet tavily-python"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "3368f330-cad6-4d35-a291-68fbf4389d98",
   "metadata": {},
   "outputs": [],
   "source": [
    "import getpass\n",
    "import os\n",
    "\n",
    "from dotenv import load_dotenv; load_dotenv()\n",
    "\n",
    "def _set_if_undefined(var: str) -> None:\n",
    "    if os.environ.get(var):\n",
    "        return\n",
    "    os.environ[var] = getpass.getpass(var)\n",
    "\n",
    "\n",
    "# Optional: Configure tracing to visualize and debug the agent\n",
    "_set_if_undefined(\"LANGCHAIN_API_KEY\")\n",
    "os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",
    "os.environ[\"LANGCHAIN_PROJECT\"] = \"Reflection\"\n",
    "\n",
    "_set_if_undefined(\"FIREWORKS_API_KEY\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f27bcc4a-aaa5-46bd-8163-3e0e90cb66e6",
   "metadata": {},
   "source": [
    "## Generate\n",
    "\n",
    "For our example, we will create a \"5 paragraph essay\" generator. First, create the generator:\n",
    "\n",
    "“系统”，  \n",
    "“你是一个论文助手，负责撰写优秀的五段式论文。”  \n",
    "“为用户的请求生成最好的论文。”  \n",
    "“如果用户提供反馈，请对之前的尝试做出修改。”\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "cc10028f-9cef-4936-9419-cbdf06d24f1e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.messages import AIMessage, BaseMessage, HumanMessage\n",
    "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
    "from langchain_fireworks import ChatFireworks\n",
    "\n",
    "prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\n",
    "            \"system\",\n",
    "            \"You are an essay assistant tasked with writing excellent 5-paragraph essays.\"\n",
    "            \" Generate the best essay possible for the user's request.\"\n",
    "            \" If the user provides critique, respond with a revised version of your previous attempts.\",\n",
    "        ),\n",
    "        MessagesPlaceholder(variable_name=\"messages\"),\n",
    "    ]\n",
    ")\n",
    "llm = ChatFireworks(\n",
    "    model=\"accounts/fireworks/models/mixtral-8x7b-instruct\",\n",
    "    max_tokens=32768\n",
    ")\n",
    "generate = prompt | llm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9bbe25dc-fd1e-4ed5-a3c8-fed830b46d12",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Title: The Eternal Relevance of The Little Prince in Modern Childhood\n",
      "\n",
      "Introduction:\n",
      "Antoine de Saint-Exupéry's The Little Prince is a timeless novella that has captured the hearts and minds of children and adults alike for over seven decades. Its enduring charm and profound wisdom have transcended generations, making it a classic staple in childhood literature. This essay explores the reasons why The Little Prince remains relevant in modern childhood.\n",
      "\n",
      "First Paragraph:\n",
      "One of the primary reasons for The Little Prince's relevance is its exploration of themes that resonate with children today. The story addresses universal aspects of childhood, such as the struggle to understand the world, the desire for friendship and love, and the pain of loss and loneliness. The Little Prince's encounters with various grown-ups, each representing different facets of adult absurdity, mirror the confusion and disillusionment children experience as they grow and navigate their way through a complex world.\n",
      "\n",
      "Second Paragraph:\n",
      "Moreover, The Little Prince offers valuable life lessons that are applicable to modern childhood. It teaches children the importance of looking beyond superficial appearances and forming meaningful connections with others. The Little Prince's friendship with the fox, which emphasizes the significance of seeing with the heart and creating bonds through shared experiences, is a powerful reminder for children to be kind, empathetic, and open to forming genuine relationships.\n",
      "\n",
      "Third Paragraph:\n",
      "The Little Prince also encourages children to question authority and challenge societal norms. Saint-Exupéry's critique of adult behavior and the rat race mentality resonates with modern children who face increasing pressure to conform to academic and social expectations. By presenting a childlike perspective that values curiosity, creativity, and imagination, The Little Prince inspires children to maintain their individuality and resist becoming mere cogs in the machine.\n",
      "\n",
      "Fourth Paragraph:\n",
      "Furthermore, The Little Prince addresses the emotional well-being of children in a world that often disregards their feelings. The story acknowledges the pain and sadness that children experience, offering comfort and validation through the character of the Little Prince. By normalizing and validating children's emotions, The Little Prince fosters emotional intelligence and resilience, equipping children with the tools they need to cope with life's challenges.\n",
      "\n",
      "Conclusion:\n",
      "In conclusion, The Little Prince remains a relevant and essential read for modern children due to its exploration of universal childhood themes, its valuable life lessons, its challenge to societal norms, and its emphasis on emotional intelligence. As children grow in a rapidly changing world, The Little Prince serves as a steadfast companion, guiding them through their journey with wisdom, humor, and heart. By embracing the timeless truths presented in The Little Prince, modern children can cultivate a sense of wonder, curiosity, and empathy, ensuring their continued growth and development as well-rounded, compassionate individuals."
     ]
    }
   ],
   "source": [
    "essay = \"\"\n",
    "request = HumanMessage(\n",
    "    content=\"Write an essay on why the little prince is relevant in modern childhood\"\n",
    ")\n",
    "for chunk in generate.stream({\"messages\": [request]}):\n",
    "    print(chunk.content, end=\"\")\n",
    "    essay += chunk.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0b276e7-c392-4eec-be75-c77bd130379d",
   "metadata": {},
   "source": [
    "### Reflect\n",
    "\n",
    "“系统”，  \n",
    "“你是一位教师，正在对一篇论文提交进行评分。生成对用户提交的批评和建议。”  \n",
    "“提供详细的建议，包括对长度、深度、风格等的要求。”"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "a705be92-88c0-4f4f-b4c2-cdcd9af8cb2c",
   "metadata": {},
   "outputs": [],
   "source": [
    "reflection_prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\n",
    "            \"system\",\n",
    "            \"You are a teacher grading an essay submission. Generate critique and recommendations for the user's submission.\"\n",
    "            \" Provide detailed recommendations, including requests for length, depth, style, etc.\",\n",
    "        ),\n",
    "        MessagesPlaceholder(variable_name=\"messages\"),\n",
    "    ]\n",
    ")\n",
    "reflect = reflection_prompt | llm"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4379fbc5",
   "metadata": {},
   "source": [
    "### 生成的教师评论：\n",
    "标题：《小王子》在现代童年的永恒相关性\n",
    "\n",
    "引言：\n",
    "安托万·德·圣埃克苏佩里的《小王子》是一部永恒的中篇小说，它已经吸引了儿童和成人超过七十年的心和思想。它持久的魅力和深刻的智慧已经超越了一代又一代，使其成为儿童文学中的经典之作。本文探讨了《小王子》为何在现代童年仍然具有相关性的原因。\n",
    "\n",
    "第一段：\n",
    "《小王子》相关性的一个主要原因是它探讨了与当今儿童产生共鸣的主题。这个故事涉及儿童普遍的方面，比如努力理解世界、对友谊和爱的渴望，以及失去和孤独的痛苦。小王子与各种成年人的邂逅，每个人都代表了成人荒谬性的不同方面，反映了儿童在成长过程中经历的困惑和幻灭感。\n",
    "\n",
    "第二段：\n",
    "此外，《小王子》提供了适用于现代童年的宝贵生活教训。它教导儿童超越表面现象，与他人建立有意义的联系。小王子与狐狸的友谊强调了用心看和通过共享经验建立联系的重要性，这是对儿童要善良、有同理心和愿意建立真正关系的有力提醒。\n",
    "\n",
    "第三段：\n",
    "《小王子》还鼓励儿童质疑权威和挑战社会规范。圣埃克苏佩里对成人行为和竞争心态的批评与现代儿童产生共鸣，他们面临着越来越大的压力，要符合学术和社会期望。通过呈现一个重视好奇心、创造力和想象力的童真视角，《小王子》激励儿童保持个性，抵制成为机器中的齿轮。\n",
    "\n",
    "第四段：\n",
    "此外，《小王子》在一个常常忽视儿童情感的世界中关注儿童的情感福祉。故事承认儿童经历的痛苦和悲伤，通过小王子这个角色提供安慰和认可。通过正常化和认可儿童的情感，《小王子》培养了情感智能和韧性，为儿童提供了应对生活挑战所需的工具。\n",
    "\n",
    "结论：\n",
    "总之，《小王子》由于其对普遍童年主题的探索、其宝贵的生活教训、对社会规范的挑战以及对情感智能的强调，仍然是现代儿童相关且必不可少的读物。随着儿童在一个迅速变化的世界中成长，《小王子》作为一个坚定的伴侣，用智慧、幽默和心灵引导他们通过他们的旅程。通过拥抱《小王子》中呈现的永恒真理，现代儿童可以培养一种惊奇、好奇心和同理心，确保他们作为全面发展、有同情心的个体的持续成长和发展。\n",
    "\n",
    "文章批评和建议：\n",
    "\n",
    "标题：你选择的标题是恰当和吸引人的。它清楚地传达了你文章的重点，同时也激起了读者的兴趣。\n",
    "\n",
    "引言：\n",
    "引言写得不错，为你的文章设定了舞台。它提供了一个清晰的论点，概述了《小王子》在现代童年的相关性原因。\n",
    "\n",
    "第一段：\n",
    "你的第一段有效地突出了《小王子》中与当今儿童产生共鸣的普遍主题。然而，考虑提供更多来自小说的具体例子来加强你的论点。此外，考虑讨论这些主题在现代童年背景下的特殊相关性，例如社交媒体和技术对儿童理解世界的影响。\n",
    "\n",
    "第二段：\n",
    "你的第二段简洁地捕捉了《小王子》传授的生活教训。为了进一步加强这一点，你可能想要包括现实世界中的例子或轶事，以展示这些教训如何在现代童年中应用。这将有助于使你的论点更加相关和吸引读者。\n",
    "\n",
    "第三段：\n",
    "你的第三段有效地论证了《小王子》挑战社会规范并鼓励儿童质疑权威。为了加强这一点，考虑讨论小说中具体的例子，这些例子展示了对成人行为的批评。此外，考虑讨论这一信息在现代童年背景下的特殊相关性，例如标准化测试的影响和符合学术和社会期望的压力。\n",
    "\n",
    "第四段：\n",
    "你的第四段有效地强调了《小王子》在现代儿童中培养情感智能的重要性。为了进一步加强这一点，考虑讨论小说如何培养现代儿童的情感智能，例如通过验证他们的情感和鼓励同理心和善良。\n",
    "\n",
    "结论：\n",
    "你的结论有效地总结了你文章的主要观点，并加强了《小王子》在现代童年的相关性。考虑以小说中的一个强有力的引用或形象结束，概括了它的永恒智慧和吸引力。\n",
    "\n",
    "建议：\n",
    "\n",
    "* 提供更多来自小说的具体例子来加强你的论点。\n",
    "* 包括现实世界中的例子或轶事，使你的论点更加相关和吸引。\n",
    "* 讨论《小王子》的主题和信息在现代童年背景下的特殊相关性。\n",
    "* 考虑扩展你文章的长度，以允许更深入的分析和讨论。\n",
    "* 确保你的文章结构良好，逻辑流畅。\n",
    "* 使用清晰和简洁的语言，并避免过于复杂的句子或行话。\n",
    "* 仔细校对你的文章，确保它没有错误和打字错误。\n",
    "\n",
    "总的来说，你的文章为《小王子》在现代童年的相关性提供了一个深思熟虑和有支持的论点。通过一些修订和扩展，它有潜力成为一篇优秀和吸引人的写作作品。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "16c5eb2a-8bce-48ab-b87d-9dacb9b64ac6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Title: The Eternal Relevance of The Little Prince in Modern Childhood\n",
      "\n",
      "Introduction:\n",
      "Antoine de Saint-Exupéry's The Little Prince is a timeless novella that has captured the hearts and minds of children and adults alike for over seven decades. Its enduring charm and profound wisdom have transcended generations, making it a classic staple in childhood literature. This essay explores the reasons why The Little Prince remains relevant in modern childhood.\n",
      "\n",
      "First Paragraph:\n",
      "One of the primary reasons for The Little Prince's relevance is its exploration of themes that resonate with children today. The story addresses universal aspects of childhood, such as the struggle to understand the world, the desire for friendship and love, and the pain of loss and loneliness. The Little Prince's encounters with various grown-ups, each representing different facets of adult absurdity, mirror the confusion and disillusionment children experience as they grow and navigate their way through a complex world.\n",
      "\n",
      "Second Paragraph:\n",
      "Moreover, The Little Prince offers valuable life lessons that are applicable to modern childhood. It teaches children the importance of looking beyond superficial appearances and forming meaningful connections with others. The Little Prince's friendship with the fox, which emphasizes the significance of seeing with the heart and creating bonds through shared experiences, is a powerful reminder for children to be kind, empathetic, and open to forming genuine relationships.\n",
      "\n",
      "Third Paragraph:\n",
      "The Little Prince also encourages children to question authority and challenge societal norms. Saint-Exupéry's critique of adult behavior and the rat race mentality resonates with modern children who face increasing pressure to conform to academic and social expectations. By presenting a childlike perspective that values curiosity, creativity, and imagination, The Little Prince inspires children to maintain their individuality and resist becoming mere cogs in the machine.\n",
      "\n",
      "Fourth Paragraph:\n",
      "Furthermore, The Little Prince addresses the emotional well-being of children in a world that often disregards their feelings. The story acknowledges the pain and sadness that children experience, offering comfort and validation through the character of the Little Prince. By normalizing and validating children's emotions, The Little Prince fosters emotional intelligence and resilience, equipping children with the tools they need to cope with life's challenges.\n",
      "\n",
      "Conclusion:\n",
      "In conclusion, The Little Prince remains a relevant and essential read for modern children due to its exploration of universal childhood themes, its valuable life lessons, its challenge to societal norms, and its emphasis on emotional intelligence. As children grow in a rapidly changing world, The Little Prince serves as a steadfast companion, guiding them through their journey with wisdom, humor, and heart. By embracing the timeless truths presented in The Little Prince, modern children can cultivate a sense of wonder, curiosity, and empathy, ensuring their continued growth and development as well-rounded, compassionate individuals.\n",
      "Essay critique and recommendations:\n",
      "\n",
      "Title: The title you have chosen is appropriate and engaging. It clearly conveys the focus of your essay while also piquing the reader's interest.\n",
      "\n",
      "Introduction:\n",
      "The introduction is well-written and sets the stage for your essay. It provides a clear thesis statement that outlines the reasons for The Little Prince's relevance in modern childhood.\n",
      "\n",
      "First Paragraph:\n",
      "Your first paragraph effectively highlights the universal themes present in The Little Prince that resonate with children today. However, consider providing more specific examples from the novella to strengthen your argument. Additionally, consider discussing how these themes are particularly relevant in the context of modern childhood, such as the impact of social media and technology on children's understanding of the world.\n",
      "\n",
      "Second Paragraph:\n",
      "Your second paragraph succinctly captures the life lessons that The Little Prince imparts. To further enhance this point, you may want to include real-world examples or anecdotes that demonstrate how these lessons can be applied in modern childhood. This would help to make your argument more relatable and engaging for your readers.\n",
      "\n",
      "Third Paragraph:\n",
      "Your third paragraph effectively argues that The Little Prince challenges societal norms and encourages children to question authority. To strengthen this point, consider discussing specific examples from the novella that demonstrate this critique of adult behavior. Additionally, consider discussing how this message is particularly relevant in the context of modern childhood, such as the impact of standardized testing and the pressure to conform to academic and social expectations.\n",
      "\n",
      "Fourth Paragraph:\n",
      "Your fourth paragraph effectively highlights the importance of emotional intelligence in The Little Prince. To further enhance this point, consider discussing how the novella fosters emotional intelligence in modern children, such as by validating their emotions and encouraging empathy and kindness.\n",
      "\n",
      "Conclusion:\n",
      "Your conclusion effectively summarizes the main points of your essay and reinforces the relevance of The Little Prince in modern childhood. Consider ending with a powerful quote or image from the novella that encapsulates its timeless wisdom and appeal.\n",
      "\n",
      "Recommendations:\n",
      "\n",
      "* Provide more specific examples from the novella to strengthen your argument.\n",
      "* Incorporate real-world examples or anecdotes to make your argument more relatable and engaging.\n",
      "* Discuss how the themes and messages of The Little Prince are particularly relevant in the context of modern childhood.\n",
      "* Consider expanding the length of your essay to allow for more in-depth analysis and discussion.\n",
      "* Ensure that your essay is well-structured and flows logically from one point to the next.\n",
      "* Use clear and concise language, and avoid overly complex sentences or jargon.\n",
      "* Proofread your essay carefully to ensure that it is free from errors and typos.\n",
      "\n",
      "Overall, your essay provides a thoughtful and well-supported argument for the relevance of The Little Prince in modern childhood. With some revisions and expansion, it has the potential to be an excellent and engaging piece of writing."
     ]
    }
   ],
   "source": [
    "reflection = \"\"\n",
    "for chunk in reflect.stream({\"messages\": [request, HumanMessage(content=essay)]}):\n",
    "    print(chunk.content, end=\"\")\n",
    "    reflection += chunk.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6daf926c-1174-4e96-91b9-57c57cfce40d",
   "metadata": {},
   "source": [
    "### Repeat\n",
    "\n",
    "And... that's all there is too it! You can repeat in a loop for a fixed number of steps, or use an LLM (or other check) to decide when the finished product is good enough.\n",
    "\n",
    "修改后的文稿：\n",
    "标题：《小王子》在现代童年的永恒相关性\n",
    "\n",
    "引言：\n",
    "引言部分写得不错，为你的文章设定了基调。它提供了一个清晰的论点，概述了《小王子》在现代童年的相关性原因。\n",
    "\n",
    "第一段：\n",
    "你的第一段有效地突出了《小王子》中与当今儿童产生共鸣的普遍主题。为了加强你的论点，让我们更深入地探讨这些主题，并探讨它们在现代童年背景下的相关性。例如，小王子在一个充满表面现象的世界中对有意义联系的渴望，反映了许多今天儿童的经历，他们可能会被社交媒体和科技的不断冲击所压倒。\n",
    "\n",
    "第二段：\n",
    "你的第二段简洁地捕捉了《小王子》传授的生活教训。为了进一步加强这一点，考虑加入现实世界中的例子或轶事，展示这些教训如何在现代童年中应用。例如，小王子强调超越表面现象，形成有意义的联系，这可以在反欺凌运动和促进同理心和善良的倡议中看到。\n",
    "\n",
    "第三段：\n",
    "你的第三段有效地论证了《小王子》挑战社会规范并鼓励儿童质疑权威。为了加强这一点，让我们讨论小说中具体的例子，这些例子展示了对成人行为的批评。例如，小王子与商人的邂逅，商人过于沉迷于自己的物质财富，而无法欣赏星星的美丽，这作为对无节制的消费主义和物质主义危险的有力提醒。\n",
    "\n",
    "第四段：\n",
    "你的第四段有效地强调了《小王子》在培养情感智能方面的重要性。为了进一步加强这一点，让我们讨论小说如何培养现代儿童的情感智能，例如通过验证他们的情感和鼓励同理心和善良。例如，小王子与狐狸的友谊教会了儿童与他人建立强大、情感联系的价值，即使这些联系是短暂或临时的。\n",
    "\n",
    "结论：\n",
    "你的结论有效地总结了你文章的主要观点，并加强了《小王子》在现代童年的相关性。要以强有力的引用或形象结束，考虑使用小说著名的结尾行：“这是我的秘密。它非常简单：只有用心去看，才能看得正确。真正重要的东西是用眼睛看不见的。”这句话概括了《小王子》的永恒智慧和吸引力，提醒我们情感智能、同理心和善良在现代童年乃至更广泛领域的重要性。\n",
    "\n",
    "建议：\n",
    "\n",
    "* 提供更多来自小说的具体例子来加强你的论点。\n",
    "* 包括现实世界中的例子或轶事，使你的论点更加相关和吸引。\n",
    "* 讨论《小王子》的主题和信息在现代童年背景下的特殊相关性。\n",
    "* 考虑扩展你文章的长度，以允许更深入的分析和讨论。\n",
    "* 确保你的文章结构良好，逻辑流畅。\n",
    "* 使用清晰和简洁的语言，并避免过于复杂的句子或行话。\n",
    "* 仔细校对你的文章，确保它没有错误和打字错误。\n",
    "\n",
    "总的来说，你的文章为《小王子》在现代童年的相关性提供了一个深思熟虑和有支持的论点。通过一些修订和扩展，它有潜力成为一篇优秀和吸引人的写作作品。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "dfbf99a8-3aa0-4e09-936e-8452c35fa84d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Title: The Eternal Relevance of The Little Prince in Modern Childhood\n",
      "\n",
      "Introduction:\n",
      "The introduction is well-written and sets the stage for your essay. It provides a clear thesis statement that outlines the reasons for The Little Prince's relevance in modern childhood.\n",
      "\n",
      "First Paragraph:\n",
      "Your first paragraph effectively highlights the universal themes present in The Little Prince that resonate with children today. To strengthen your argument, let's delve deeper into these themes and explore their relevance in the context of modern childhood. For instance, the Little Prince's longing for meaningful connections amidst a world of superficiality mirrors the experiences of many children today, who may feel overwhelmed by the constant barrage of social media and technology.\n",
      "\n",
      "Second Paragraph:\n",
      "Your second paragraph succinctly captures the life lessons that The Little Prince imparts. To further enhance this point, consider incorporating real-world examples or anecdotes that demonstrate how these lessons can be applied in modern childhood. For example, the Little Prince's emphasis on looking beyond superficial appearances and forming meaningful connections can be seen in the popularity of anti-bullying campaigns and initiatives that promote empathy and kindness.\n",
      "\n",
      "Third Paragraph:\n",
      "Your third paragraph effectively argues that The Little Prince challenges societal norms and encourages children to question authority. To strengthen this point, let's discuss specific examples from the novella that demonstrate this critique of adult behavior. For instance, the Little Prince's encounters with the businessman, who is too preoccupied with his material possessions to appreciate the beauty of the stars, serve as a powerful reminder of the dangers of unchecked consumerism and materialism.\n",
      "\n",
      "Fourth Paragraph:\n",
      "Your fourth paragraph effectively highlights the importance of emotional intelligence in The Little Prince. To further enhance this point, let's discuss how the novella fosters emotional intelligence in modern children, such as by validating their emotions and encouraging empathy and kindness. For example, the Little Prince's friendship with the fox teaches children the value of building strong, emotional connections with others, even if those connections are fleeting or temporary.\n",
      "\n",
      "Conclusion:\n",
      "Your conclusion effectively summarizes the main points of your essay and reinforces the relevance of The Little Prince in modern childhood. To end with a powerful quote or image, consider using the novella's famous closing lines: \"Here is my secret. It is very simple: It is only with the heart that one can see rightly. What is essential is invisible to the eye.\" This quote encapsulates the timeless wisdom and appeal of The Little Prince, reminding us of the importance of emotional intelligence, empathy, and kindness in modern childhood and beyond.\n",
      "\n",
      "Recommendations:\n",
      "\n",
      "* Provide more specific examples from the novella to strengthen your argument.\n",
      "* Incorporate real-world examples or anecdotes to make your argument more relatable and engaging.\n",
      "* Discuss how the themes and messages of The Little Prince are particularly relevant in the context of modern childhood.\n",
      "* Consider expanding the length of your essay to allow for more in-depth analysis and discussion.\n",
      "* Ensure that your essay is well-structured and flows logically from one point to the next.\n",
      "* Use clear and concise language, and avoid overly complex sentences or jargon.\n",
      "* Proofread your essay carefully to ensure that it is free from errors and typos.\n",
      "\n",
      "Overall, your essay provides a thoughtful and well-supported argument for the relevance of The Little Prince in modern childhood. With some revisions and expansion, it has the potential to be an excellent and engaging piece of writing."
     ]
    }
   ],
   "source": [
    "for chunk in generate.stream(\n",
    "    {\"messages\": [request, AIMessage(content=essay), HumanMessage(content=reflection)]}\n",
    "):\n",
    "    print(chunk.content, end=\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b63a9d93-a14d-4e41-a4bb-a4cd31713f44",
   "metadata": {},
   "source": [
    "## Define graph\n",
    "\n",
    "Now that we've shown each step in isolation, we can wire it up in a graph."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "9e9a9d7c-5d2e-4194-b745-4511ec20db76",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Annotated, List, Sequence\n",
    "from langgraph.graph import END, StateGraph, START\n",
    "from langgraph.graph.message import add_messages\n",
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from typing_extensions import TypedDict\n",
    "\n",
    "\n",
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "\n",
    "\n",
    "async def generation_node(state: State) -> State:\n",
    "    return {\"messages\": [await generate.ainvoke(state['messages'])]}\n",
    "\n",
    "\n",
    "async def reflection_node(state: State) -> State:\n",
    "    # Other messages we need to adjust\n",
    "    cls_map = {\"ai\": HumanMessage, \"human\": AIMessage}\n",
    "    # First message is the original user request. We hold it the same for all nodes\n",
    "    translated = [state['messages'][0]] + [\n",
    "        cls_map[msg.type](content=msg.content) for msg in state['messages'][1:]\n",
    "    ]\n",
    "    res = await reflect.ainvoke(translated)\n",
    "    # We treat the output of this as human feedback for the generator\n",
    "    return {\"messages\": [HumanMessage(content=res.content)]}\n",
    "\n",
    "\n",
    "builder = StateGraph(State)\n",
    "builder.add_node(\"generate\", generation_node)\n",
    "builder.add_node(\"reflect\", reflection_node)\n",
    "builder.add_edge(START, \"generate\")\n",
    "\n",
    "\n",
    "def should_continue(state: State):\n",
    "    if len(state[\"messages\"]) > 6:\n",
    "        # End after 3 iterations\n",
    "        return END\n",
    "    return \"reflect\"\n",
    "\n",
    "\n",
    "\n",
    "builder.add_conditional_edges(\"generate\", should_continue)\n",
    "builder.add_edge(\"reflect\", \"generate\")\n",
    "memory = MemorySaver()\n",
    "graph = builder.compile(checkpointer=memory)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "010ce60a-8b7d-4258-99d1-52705146844f",
   "metadata": {},
   "outputs": [],
   "source": [
    "config = {\"configurable\": {\"thread_id\": \"1\"}}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "06263a07-8a15-4ec3-b692-1c6cef3b1c1f",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'generate': {'messages': [AIMessage(content='Title: The Little Prince: A Topical Allegory for Modern Life\\n\\nIntroduction:\\nAntoine de Saint-Exupéry\\'s \"The Little Prince\" is a classic novella that has captured the hearts of millions since its publication in 1943. While it might be easy to dismiss this work as a children\\'s story, its profound themes and timeless message make it a relevant and topical piece in modern life. This essay will explore the allegorical nature of \"The Little Prince\" and discuss how its message can be applied to the complexities of the modern world.\\n\\nBody Paragraph 1 - The Allegory of the Little Prince:\\n\"The Little Prince\" is an allegorical tale that explores various aspects of the human condition through its whimsical characters and situations. The Little Prince himself represents innocence, curiosity, and the importance of human connection. As the story unfolds, readers encounter different characters that symbolize various aspects of adult life, such as vanity, materialism, and authority. These representations allow the story to transcend age and culture, making it relatable to a wide range of readers, even in the modern context.\\n\\nBody Paragraph 2 - The Relevance of the Little Prince\\'s Message:\\nThe Little Prince\\'s message is centered around the importance of looking beyond superficial appearances and forming meaningful connections with others. In a world increasingly dominated by technology and social media, where surface-level interactions are commonplace, this message is more relevant than ever. The Little Prince encourages readers to cherish and nurture genuine relationships, reminding us that true happiness and fulfillment come from understanding and empathizing with others.\\n\\nBody Paragraph 3 - The Critique of Modern Society:\\n\"The Little Prince\" also offers a critique of modern society, highlighting the dangers of materialism, consumerism, and the pursuit of power. These themes resonate strongly in today\\'s world, where wealth inequality and environmental degradation are pressing issues. The story serves as a reminder that the pursuit of material possessions and status often comes at the expense of our own happiness and the well-being of our planet.\\n\\nConclusion:\\nIn conclusion, \"The Little Prince\" remains a topical and relevant work in modern life due to its allegorical nature, timeless message, and critique of modern society. Its exploration of human connections, materialism, and the pursuit of power offers valuable insights for readers of all ages. By embracing the story\\'s wisdom, we can better navigate the complexities of the modern world and foster a more compassionate, sustainable, and interconnected society.', response_metadata={'token_usage': {'prompt_tokens': 72, 'total_tokens': 632, 'completion_tokens': 560}, 'model_name': 'accounts/fireworks/models/mixtral-8x7b-instruct', 'system_fingerprint': '', 'finish_reason': 'stop', 'logprobs': None}, id='run-b39a25ab-24f6-42d0-96c2-0f74c3ecc8f7-0', usage_metadata={'input_tokens': 72, 'output_tokens': 560, 'total_tokens': 632})]}}\n",
      "---\n",
      "{'reflect': {'messages': [HumanMessage(content='Essay Critique and Recommendations:\\n\\nTitle: The Little Prince: A Topical Allegory for Modern Life\\n\\nIntroduction:\\nThe introduction effectively sets the stage for the essay by providing background information on \"The Little Prince\" and its relevance in modern life. However, consider adding a hook to engage the reader\\'s attention and create a stronger first impression.\\n\\nBody Paragraph 1 - The Allegory of the Little Prince:\\nThis paragraph provides a clear explanation of the allegorical nature of \"The Little Prince.\" To enhance this section, consider offering specific examples from the text to illustrate how the characters and situations symbolize various aspects of adult life. This will strengthen your analysis and make it more engaging for the reader.\\n\\nBody Paragraph 2 - The Relevance of the Little Prince\\'s Message:\\nThe relevance of the Little Prince\\'s message is well-articulated in this paragraph. To further strengthen your argument, consider discussing the consequences of ignoring this message in the context of modern society. This will help emphasize the importance of the Little Prince\\'s wisdom and its relevance to contemporary issues.\\n\\nBody Paragraph 3 - The Critique of Modern Society:\\nThis paragraph effectively highlights the story\\'s critique of modern society. To deepen your analysis, explore how the themes of materialism, consumerism, and the pursuit of power interconnect and contribute to the challenges faced by modern society. Additionally, consider discussing potential solutions or actions inspired by the Little Prince\\'s message that could help address these issues.\\n\\nConclusion:\\nThe conclusion effectively summarizes the main points of the essay and emphasizes the relevance of \"The Little Prince\" in modern life. To further enhance this section, consider incorporating a thought-provoking question or statement that encourages readers to reflect on the story\\'s message and its implications for their own lives.\\n\\nRecommendations:\\n1. Expand the essay to approximately 1,200-1,500 words to allow for a more in-depth analysis.\\n2. Incorporate specific examples and quotes from \"The Little Prince\" to support your arguments and engage the reader.\\n3. Ensure that each body paragraph contains a clear thesis statement, supporting evidence, and analysis.\\n4. Consider discussing counterarguments or potential criticisms of the Little Prince\\'s message to add depth and complexity to your essay.\\n5. Revise and edit the essay for clarity, coherence, and grammar.')]}}\n",
      "---\n",
      "{'generate': {'messages': [AIMessage(content='Title: The Little Prince: A Topical Allegory for Modern Life\\n\\nIntroduction:\\nIn Antoine de Saint-Exupéry\\'s classic novella \"The Little Prince,\" a young boy embarks on a journey through the universe, meeting various characters that symbolize different aspects of adult life. This timeless tale, published in 1943, remains incredibly relevant in today\\'s modern world. Its allegorical nature, thought-provoking message, and critique of modern society offer invaluable insights for readers of all ages. This essay will explore the allegory of \"The Little Prince,\" analyze the relevance of its message, and discuss its critique of modern society, demonstrating its topicality in contemporary life.\\n\\nBody Paragraph 1 - The Allegory of the Little Prince:\\n\"The Little Prince\" is an allegorical tale that uses whimsical characters and situations to explore various aspects of the human condition. For instance, the king represents authority without substance, while the businessman embodies the futility of materialism. The fox, conversely, symbolizes the importance of forming genuine connections and nurturing meaningful relationships. These allegorical representations allow the story to transcend age and culture, making it relatable to a wide range of readers, even in the modern context.\\n\\nBody Paragraph 2 - The Relevance of the Little Prince\\'s Message:\\nThe Little Prince\\'s message is centered around the importance of looking beyond superficial appearances and forming meaningful connections with others. In a world increasingly dominated by technology and social media, where surface-level interactions are commonplace, this message is more relevant than ever. Neglecting this message can lead to feelings of isolation, loneliness, and dissatisfaction. By embracing the story\\'s wisdom, we can prioritize genuine relationships, fostering a more compassionate and interconnected society.\\n\\nBody Paragraph 3 - The Critique of Modern Society:\\n\"The Little Prince\" offers a critique of modern society, highlighting the dangers of materialism, consumerism, and the pursuit of power. These themes resonate strongly in today\\'s world, where wealth inequality and environmental degradation are pressing issues. The story serves as a reminder that the pursuit of material possessions and status often comes at the expense of our own happiness and the well-being of our planet. To address these challenges, we must reevaluate our priorities, focusing on sustainability, empathy, and the cultivation of meaningful relationships.\\n\\nConclusion:\\nIn conclusion, \"The Little Prince\" remains a topical and relevant work in modern life due to its allegorical nature, timeless message, and critique of modern society. Its exploration of human connections, materialism, and the pursuit of power offers valuable insights for readers of all ages. By embracing the story\\'s wisdom, we can better navigate the complexities of the modern world and foster a more compassionate, sustainable, and interconnected society. As the Little Prince so eloquently states, \"What is essential is invisible to the eye,\" reminding us that true happiness and fulfillment come from understanding and empathizing with others.\\n\\nExpanded Essay Recommendations:\\n\\n1. Expand the essay to approximately 1,200-1,500 words to allow for a more in-depth analysis.\\n2. Incorporate specific examples and quotes from \"The Little Prince\" to support your arguments and engage the reader. For instance, use quotes like, \"You become responsible, forever, for what you have tamed,\" to emphasize the importance of forming genuine connections.\\n3. Ensure that each body paragraph contains a clear thesis statement, supporting evidence, and analysis.\\n4. Consider discussing counterarguments or potential criticisms of the Little Prince\\'s message to add depth and complexity to your essay. For example, explore the idea that the pursuit of material possessions can provide a sense of security and comfort.\\n5. Revise and edit the essay for clarity, coherence, and grammar. Ensure that transitions between paragraphs are smooth and that your arguments flow logically.', response_metadata={'token_usage': {'prompt_tokens': 1168, 'total_tokens': 2044, 'completion_tokens': 876}, 'model_name': 'accounts/fireworks/models/mixtral-8x7b-instruct', 'system_fingerprint': '', 'finish_reason': 'stop', 'logprobs': None}, id='run-9bfc9ff2-3186-43f5-8b75-498d532d8d1a-0', usage_metadata={'input_tokens': 1168, 'output_tokens': 876, 'total_tokens': 2044})]}}\n",
      "---\n",
      "{'reflect': {'messages': [HumanMessage(content='Your revised essay demonstrates a clear understanding of the assignment and the source material. Here are some additional recommendations to further enhance your essay:\\n\\n1. Consider adding more nuance to your analysis of the allegory in Body Paragraph 1. You could explore how the Little Prince himself evolves throughout the story, representing not just innocence and curiosity, but also the capacity for growth and self-discovery.\\n\\n2. In Body Paragraph 2, you could delve deeper into the psychological consequences of neglecting genuine relationships. Research has shown that loneliness and social isolation can have significant impacts on mental and physical health. Incorporating these findings would strengthen your argument about the importance of the Little Prince\\'s message.\\n\\n3. For Body Paragraph 3, you could provide specific examples of how materialism and consumerism contribute to wealth inequality and environmental degradation. This would make your critique of modern society more concrete and compelling.\\n\\n4. In your conclusion, you could discuss how the Little Prince\\'s message can be applied to various aspects of modern life, such as education, politics, and personal relationships. This would demonstrate the wide-ranging relevance of the story and inspire readers to reflect on its implications for their own lives.\\n\\n5. Throughout the essay, make sure to cite secondary sources to support your analysis. This will add credibility to your arguments and demonstrate your engagement with existing scholarship on \"The Little Prince.\"\\n\\n6. Finally, proofread your essay carefully to ensure that it is free of grammatical errors and awkward phrasing. Consider asking a peer or mentor to review your work and provide feedback. A fresh pair of eyes can help you identify areas for improvement and ensure that your essay is polished and professional.')]}}\n",
      "---\n",
      "{'generate': {'messages': [AIMessage(content='Title: The Little Prince: A Topical Allegory for Modern Life\\n\\nIntroduction:\\nAntoine de Saint-Exupéry\\'s \"The Little Prince\" is a timeless novella that has captured the hearts of millions since its publication in 1943. While it might be easy to dismiss this work as a children\\'s story, its profound themes and timeless message make it a relevant and topical piece in modern life. This essay will explore the allegorical nature of \"The Little Prince,\" analyze the psychological and societal consequences of neglecting its message, and discuss its critique of modern society, demonstrating its topicality in contemporary life.\\n\\nBody Paragraph 1 - The Allegory of the Little Prince:\\n\"The Little Prince\" is an allegorical tale that uses whimsical characters and situations to explore various aspects of the human condition. The Little Prince himself represents innocence, curiosity, and the importance of human connection, but he also embodies the capacity for growth and self-discovery. As the story unfolds, readers encounter different characters that symbolize various aspects of adult life, such as vanity, materialism, and authority. These representations allow the story to transcend age and culture, making it relatable to a wide range of readers, even in the modern context.\\n\\nBody Paragraph 2 - The Relevance of the Little Prince\\'s Message:\\nThe Little Prince\\'s message is centered around the importance of looking beyond superficial appearances and forming meaningful connections with others. In a world increasingly dominated by technology and social media, where surface-level interactions are commonplace, this message is more relevant than ever. Neglecting this message can lead to feelings of isolation, loneliness, and dissatisfaction, which can have significant impacts on mental and physical health. By embracing the story\\'s wisdom, we can prioritize genuine relationships, fostering a more compassionate and interconnected society.\\n\\nBody Paragraph 3 - The Critique of Modern Society:\\n\"The Little Prince\" offers a critique of modern society, highlighting the dangers of materialism, consumerism, and the pursuit of power. Materialism and consumerism contribute to wealth inequality and environmental degradation by promoting unsustainable practices and exacerbating social and economic disparities. For instance, the overconsumption of resources leads to deforestation, climate change, and the exploitation of marginalized communities. To address these challenges, we must reevaluate our priorities, focusing on sustainability, empathy, and the cultivation of meaningful relationships.\\n\\nConclusion:\\nIn conclusion, \"The Little Prince\" remains a topical and relevant work in modern life due to its allegorical nature, timeless message, and critique of modern society. Its exploration of human connections, materialism, and the pursuit of power offers valuable insights for readers of all ages. The Little Prince\\'s message can be applied to various aspects of modern life, such as education, politics, and personal relationships, inspiring readers to reflect on its implications for their own lives. By embracing the story\\'s wisdom, we can better navigate the complexities of the modern world and foster a more compassionate, sustainable, and interconnected society.\\n\\nTo further enhance your essay, consider incorporating secondary sources to support your analysis, and proofread your work carefully to ensure that it is free of grammatical errors and awkward phrasing. A fresh pair of eyes can help you identify areas for improvement and ensure that your essay is polished and professional.', response_metadata={'token_usage': {'prompt_tokens': 2419, 'total_tokens': 3164, 'completion_tokens': 745}, 'model_name': 'accounts/fireworks/models/mixtral-8x7b-instruct', 'system_fingerprint': '', 'finish_reason': 'stop', 'logprobs': None}, id='run-eabbd349-2b3a-4bcf-a89b-716b25471846-0', usage_metadata={'input_tokens': 2419, 'output_tokens': 745, 'total_tokens': 3164})]}}\n",
      "---\n",
      "{'reflect': {'messages': [HumanMessage(content='Thank you for the feedback and recommendations. I have incorporated some of the suggestions to further enhance the essay:\\n\\nTitle: The Little Prince: A Topical Allegory for Modern Life\\n\\nIntroduction:\\nAntoine de Saint-Exupéry\\'s \"The Little Prince\" is a timeless novella that has captured the hearts of millions since its publication in 1943. While it might be easy to dismiss this work as a children\\'s story, its profound themes and timeless message make it a relevant and topical piece in modern life. This essay will explore the allegorical nature of \"The Little Prince,\" analyze the psychological and societal consequences of neglecting its message, and discuss its critique of modern society, demonstrating its topicality in contemporary life.\\n\\nBody Paragraph 1 - The Allegory of the Little Prince:\\n\"The Little Prince\" is an allegorical tale that uses whimsical characters and situations to explore various aspects of the human condition. The Little Prince himself represents innocence, curiosity, and the importance of human connection, but he also embodies the capacity for growth and self-discovery. As the story unfolds, readers encounter different characters that symbolize various aspects of adult life, such as vanity, materialism, and authority. For instance, the king represents authority without substance, while the businessman embodies the futility of materialism. The fox, conversely, symbolizes the importance of forming genuine connections and nurturing meaningful relationships. These allegorical representations allow the story to transcend age and culture, making it relatable to a wide range of readers, even in the modern context.\\n\\nBody Paragraph 2 - The Relevance of the Little Prince\\'s Message:\\nThe Little Prince\\'s message is centered around the importance of looking beyond superficial appearances and forming meaningful connections with others. In a world increasingly dominated by technology and social media, where surface-level interactions are commonplace, this message is more relevant than ever. Neglecting this message can lead to feelings of isolation, loneliness, and dissatisfaction, which can have significant impacts on mental and physical health. Research has shown that loneliness and social isolation can increase the risk of depression, anxiety, and heart disease (Holt-Lunstad, 2015). By embracing the story\\'s wisdom, we can prioritize genuine relationships, fostering a more compassionate and interconnected society.\\n\\nBody Paragraph 3 - The Critique of Modern Society:\\n\"The Little Prince\" offers a critique of modern society, highlighting the dangers of materialism, consumerism, and the pursuit of power. Materialism and consumerism contribute to wealth inequality and environmental degradation by promoting unsustainable practices and exacerbating social and economic disparities. For instance, the overconsumption of resources leads to deforestation, climate change, and the exploitation of marginalized communities (Jackson, 2017). To address these challenges, we must reevaluate our priorities, focusing on sustainability, empathy, and the cultivation of meaningful relationships.\\n\\nConclusion:\\nIn conclusion, \"The Little Prince\" remains a topical and relevant work in modern life due to its allegorical nature, timeless message, and critique of modern society. Its exploration of human connections, materialism, and the pursuit of power offers valuable insights for readers of all ages. The Little Prince\\'s message can be applied to various aspects of modern life, such as education, politics, and personal relationships, inspiring readers to reflect on its implications for their own lives. By embracing the story\\'s wisdom, we can better navigate the complexities of the modern world and foster a more compassionate, sustainable, and interconnected society.\\n\\nReferences:\\nHolt-Lunstad, J. (2015). The Loneliness Paradox. American Psychological Association.\\nJackson, T. (2017). Prosperity without Growth: Economics for a Finite Planet. Routledge.')]}}\n",
      "---\n",
      "{'generate': {'messages': [AIMessage(content='Your revised essay demonstrates a clear understanding of the assignment and the source material, and you have effectively incorporated the suggestions provided. The addition of research findings and specific examples has strengthened your argument and added credibility to your analysis. Your essay now provides a more nuanced exploration of the allegory, the relevance of the Little Prince\\'s message, and the critique of modern society.\\n\\nHere are some final recommendations to further enhance your essay:\\n\\n1. Ensure that your essay adheres to the required citation style (e.g., MLA, APA, or Chicago) and that all in-text citations and references are formatted correctly.\\n2. Double-check your essay for any grammatical errors, awkward phrasing, or unclear sentences. A well-written essay is not only easier to read but also more persuasive and engaging.\\n3. Consider adding a brief introduction to each body paragraph to provide context and guide the reader through your analysis. This will help ensure that your essay flows logically and that your arguments are easy to follow.\\n4. As a final step, ask a peer or mentor to review your work and provide feedback. A fresh pair of eyes can help you identify areas for improvement and ensure that your essay is polished and professional.\\n\\nOverall, your essay provides a thoughtful and engaging exploration of \"The Little Prince\" and its relevance in modern life. By incorporating the recommendations provided, you can further enhance your analysis and create a truly exceptional piece of writing.', response_metadata={'token_usage': {'prompt_tokens': 4034, 'total_tokens': 4354, 'completion_tokens': 320}, 'model_name': 'accounts/fireworks/models/mixtral-8x7b-instruct', 'system_fingerprint': '', 'finish_reason': 'stop', 'logprobs': None}, id='run-9c805bb5-01f4-4461-acf8-509f7440d31d-0', usage_metadata={'input_tokens': 4034, 'output_tokens': 320, 'total_tokens': 4354})]}}\n",
      "---\n"
     ]
    }
   ],
   "source": [
    "async for event in graph.astream({\n",
    "    \"messages\": [\n",
    "        HumanMessage(\n",
    "            content=\"Generate an essay on the topicality of The Little Prince and its message in modern life\"\n",
    "        )\n",
    "    ],\n",
    "}, config):\n",
    "    print(event)\n",
    "    print(\"---\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "ced83251-8edc-483d-a03f-5bd884ea8d28",
   "metadata": {},
   "outputs": [],
   "source": [
    "state = graph.get_state(config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "394bf0df-fc28-4104-a278-a56c9cb8b10c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "Generate an essay on the topicality of The Little Prince and its message in modern life\n",
      "\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "Title: The Little Prince: A Topical Allegory for Modern Life\n",
      "\n",
      "Introduction:\n",
      "Antoine de Saint-Exupéry's \"The Little Prince\" is a classic novella that has captured the hearts of millions since its publication in 1943. While it might be easy to dismiss this work as a children's story, its profound themes and timeless message make it a relevant and topical piece in modern life. This essay will explore the allegorical nature of \"The Little Prince\" and discuss how its message can be applied to the complexities of the modern world.\n",
      "\n",
      "Body Paragraph 1 - The Allegory of the Little Prince:\n",
      "\"The Little Prince\" is an allegorical tale that explores various aspects of the human condition through its whimsical characters and situations. The Little Prince himself represents innocence, curiosity, and the importance of human connection. As the story unfolds, readers encounter different characters that symbolize various aspects of adult life, such as vanity, materialism, and authority. These representations allow the story to transcend age and culture, making it relatable to a wide range of readers, even in the modern context.\n",
      "\n",
      "Body Paragraph 2 - The Relevance of the Little Prince's Message:\n",
      "The Little Prince's message is centered around the importance of looking beyond superficial appearances and forming meaningful connections with others. In a world increasingly dominated by technology and social media, where surface-level interactions are commonplace, this message is more relevant than ever. The Little Prince encourages readers to cherish and nurture genuine relationships, reminding us that true happiness and fulfillment come from understanding and empathizing with others.\n",
      "\n",
      "Body Paragraph 3 - The Critique of Modern Society:\n",
      "\"The Little Prince\" also offers a critique of modern society, highlighting the dangers of materialism, consumerism, and the pursuit of power. These themes resonate strongly in today's world, where wealth inequality and environmental degradation are pressing issues. The story serves as a reminder that the pursuit of material possessions and status often comes at the expense of our own happiness and the well-being of our planet.\n",
      "\n",
      "Conclusion:\n",
      "In conclusion, \"The Little Prince\" remains a topical and relevant work in modern life due to its allegorical nature, timeless message, and critique of modern society. Its exploration of human connections, materialism, and the pursuit of power offers valuable insights for readers of all ages. By embracing the story's wisdom, we can better navigate the complexities of the modern world and foster a more compassionate, sustainable, and interconnected society.\n",
      "\n",
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "Essay Critique and Recommendations:\n",
      "\n",
      "Title: The Little Prince: A Topical Allegory for Modern Life\n",
      "\n",
      "Introduction:\n",
      "The introduction effectively sets the stage for the essay by providing background information on \"The Little Prince\" and its relevance in modern life. However, consider adding a hook to engage the reader's attention and create a stronger first impression.\n",
      "\n",
      "Body Paragraph 1 - The Allegory of the Little Prince:\n",
      "This paragraph provides a clear explanation of the allegorical nature of \"The Little Prince.\" To enhance this section, consider offering specific examples from the text to illustrate how the characters and situations symbolize various aspects of adult life. This will strengthen your analysis and make it more engaging for the reader.\n",
      "\n",
      "Body Paragraph 2 - The Relevance of the Little Prince's Message:\n",
      "The relevance of the Little Prince's message is well-articulated in this paragraph. To further strengthen your argument, consider discussing the consequences of ignoring this message in the context of modern society. This will help emphasize the importance of the Little Prince's wisdom and its relevance to contemporary issues.\n",
      "\n",
      "Body Paragraph 3 - The Critique of Modern Society:\n",
      "This paragraph effectively highlights the story's critique of modern society. To deepen your analysis, explore how the themes of materialism, consumerism, and the pursuit of power interconnect and contribute to the challenges faced by modern society. Additionally, consider discussing potential solutions or actions inspired by the Little Prince's message that could help address these issues.\n",
      "\n",
      "Conclusion:\n",
      "The conclusion effectively summarizes the main points of the essay and emphasizes the relevance of \"The Little Prince\" in modern life. To further enhance this section, consider incorporating a thought-provoking question or statement that encourages readers to reflect on the story's message and its implications for their own lives.\n",
      "\n",
      "Recommendations:\n",
      "1. Expand the essay to approximately 1,200-1,500 words to allow for a more in-depth analysis.\n",
      "2. Incorporate specific examples and quotes from \"The Little Prince\" to support your arguments and engage the reader.\n",
      "3. Ensure that each body paragraph contains a clear thesis statement, supporting evidence, and analysis.\n",
      "4. Consider discussing counterarguments or potential criticisms of the Little Prince's message to add depth and complexity to your essay.\n",
      "5. Revise and edit the essay for clarity, coherence, and grammar.\n",
      "\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "Title: The Little Prince: A Topical Allegory for Modern Life\n",
      "\n",
      "Introduction:\n",
      "In Antoine de Saint-Exupéry's classic novella \"The Little Prince,\" a young boy embarks on a journey through the universe, meeting various characters that symbolize different aspects of adult life. This timeless tale, published in 1943, remains incredibly relevant in today's modern world. Its allegorical nature, thought-provoking message, and critique of modern society offer invaluable insights for readers of all ages. This essay will explore the allegory of \"The Little Prince,\" analyze the relevance of its message, and discuss its critique of modern society, demonstrating its topicality in contemporary life.\n",
      "\n",
      "Body Paragraph 1 - The Allegory of the Little Prince:\n",
      "\"The Little Prince\" is an allegorical tale that uses whimsical characters and situations to explore various aspects of the human condition. For instance, the king represents authority without substance, while the businessman embodies the futility of materialism. The fox, conversely, symbolizes the importance of forming genuine connections and nurturing meaningful relationships. These allegorical representations allow the story to transcend age and culture, making it relatable to a wide range of readers, even in the modern context.\n",
      "\n",
      "Body Paragraph 2 - The Relevance of the Little Prince's Message:\n",
      "The Little Prince's message is centered around the importance of looking beyond superficial appearances and forming meaningful connections with others. In a world increasingly dominated by technology and social media, where surface-level interactions are commonplace, this message is more relevant than ever. Neglecting this message can lead to feelings of isolation, loneliness, and dissatisfaction. By embracing the story's wisdom, we can prioritize genuine relationships, fostering a more compassionate and interconnected society.\n",
      "\n",
      "Body Paragraph 3 - The Critique of Modern Society:\n",
      "\"The Little Prince\" offers a critique of modern society, highlighting the dangers of materialism, consumerism, and the pursuit of power. These themes resonate strongly in today's world, where wealth inequality and environmental degradation are pressing issues. The story serves as a reminder that the pursuit of material possessions and status often comes at the expense of our own happiness and the well-being of our planet. To address these challenges, we must reevaluate our priorities, focusing on sustainability, empathy, and the cultivation of meaningful relationships.\n",
      "\n",
      "Conclusion:\n",
      "In conclusion, \"The Little Prince\" remains a topical and relevant work in modern life due to its allegorical nature, timeless message, and critique of modern society. Its exploration of human connections, materialism, and the pursuit of power offers valuable insights for readers of all ages. By embracing the story's wisdom, we can better navigate the complexities of the modern world and foster a more compassionate, sustainable, and interconnected society. As the Little Prince so eloquently states, \"What is essential is invisible to the eye,\" reminding us that true happiness and fulfillment come from understanding and empathizing with others.\n",
      "\n",
      "Expanded Essay Recommendations:\n",
      "\n",
      "1. Expand the essay to approximately 1,200-1,500 words to allow for a more in-depth analysis.\n",
      "2. Incorporate specific examples and quotes from \"The Little Prince\" to support your arguments and engage the reader. For instance, use quotes like, \"You become responsible, forever, for what you have tamed,\" to emphasize the importance of forming genuine connections.\n",
      "3. Ensure that each body paragraph contains a clear thesis statement, supporting evidence, and analysis.\n",
      "4. Consider discussing counterarguments or potential criticisms of the Little Prince's message to add depth and complexity to your essay. For example, explore the idea that the pursuit of material possessions can provide a sense of security and comfort.\n",
      "5. Revise and edit the essay for clarity, coherence, and grammar. Ensure that transitions between paragraphs are smooth and that your arguments flow logically.\n",
      "\n",
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "Your revised essay demonstrates a clear understanding of the assignment and the source material. Here are some additional recommendations to further enhance your essay:\n",
      "\n",
      "1. Consider adding more nuance to your analysis of the allegory in Body Paragraph 1. You could explore how the Little Prince himself evolves throughout the story, representing not just innocence and curiosity, but also the capacity for growth and self-discovery.\n",
      "\n",
      "2. In Body Paragraph 2, you could delve deeper into the psychological consequences of neglecting genuine relationships. Research has shown that loneliness and social isolation can have significant impacts on mental and physical health. Incorporating these findings would strengthen your argument about the importance of the Little Prince's message.\n",
      "\n",
      "3. For Body Paragraph 3, you could provide specific examples of how materialism and consumerism contribute to wealth inequality and environmental degradation. This would make your critique of modern society more concrete and compelling.\n",
      "\n",
      "4. In your conclusion, you could discuss how the Little Prince's message can be applied to various aspects of modern life, such as education, politics, and personal relationships. This would demonstrate the wide-ranging relevance of the story and inspire readers to reflect on its implications for their own lives.\n",
      "\n",
      "5. Throughout the essay, make sure to cite secondary sources to support your analysis. This will add credibility to your arguments and demonstrate your engagement with existing scholarship on \"The Little Prince.\"\n",
      "\n",
      "6. Finally, proofread your essay carefully to ensure that it is free of grammatical errors and awkward phrasing. Consider asking a peer or mentor to review your work and provide feedback. A fresh pair of eyes can help you identify areas for improvement and ensure that your essay is polished and professional.\n",
      "\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "Title: The Little Prince: A Topical Allegory for Modern Life\n",
      "\n",
      "Introduction:\n",
      "Antoine de Saint-Exupéry's \"The Little Prince\" is a timeless novella that has captured the hearts of millions since its publication in 1943. While it might be easy to dismiss this work as a children's story, its profound themes and timeless message make it a relevant and topical piece in modern life. This essay will explore the allegorical nature of \"The Little Prince,\" analyze the psychological and societal consequences of neglecting its message, and discuss its critique of modern society, demonstrating its topicality in contemporary life.\n",
      "\n",
      "Body Paragraph 1 - The Allegory of the Little Prince:\n",
      "\"The Little Prince\" is an allegorical tale that uses whimsical characters and situations to explore various aspects of the human condition. The Little Prince himself represents innocence, curiosity, and the importance of human connection, but he also embodies the capacity for growth and self-discovery. As the story unfolds, readers encounter different characters that symbolize various aspects of adult life, such as vanity, materialism, and authority. These representations allow the story to transcend age and culture, making it relatable to a wide range of readers, even in the modern context.\n",
      "\n",
      "Body Paragraph 2 - The Relevance of the Little Prince's Message:\n",
      "The Little Prince's message is centered around the importance of looking beyond superficial appearances and forming meaningful connections with others. In a world increasingly dominated by technology and social media, where surface-level interactions are commonplace, this message is more relevant than ever. Neglecting this message can lead to feelings of isolation, loneliness, and dissatisfaction, which can have significant impacts on mental and physical health. By embracing the story's wisdom, we can prioritize genuine relationships, fostering a more compassionate and interconnected society.\n",
      "\n",
      "Body Paragraph 3 - The Critique of Modern Society:\n",
      "\"The Little Prince\" offers a critique of modern society, highlighting the dangers of materialism, consumerism, and the pursuit of power. Materialism and consumerism contribute to wealth inequality and environmental degradation by promoting unsustainable practices and exacerbating social and economic disparities. For instance, the overconsumption of resources leads to deforestation, climate change, and the exploitation of marginalized communities. To address these challenges, we must reevaluate our priorities, focusing on sustainability, empathy, and the cultivation of meaningful relationships.\n",
      "\n",
      "Conclusion:\n",
      "In conclusion, \"The Little Prince\" remains a topical and relevant work in modern life due to its allegorical nature, timeless message, and critique of modern society. Its exploration of human connections, materialism, and the pursuit of power offers valuable insights for readers of all ages. The Little Prince's message can be applied to various aspects of modern life, such as education, politics, and personal relationships, inspiring readers to reflect on its implications for their own lives. By embracing the story's wisdom, we can better navigate the complexities of the modern world and foster a more compassionate, sustainable, and interconnected society.\n",
      "\n",
      "To further enhance your essay, consider incorporating secondary sources to support your analysis, and proofread your work carefully to ensure that it is free of grammatical errors and awkward phrasing. A fresh pair of eyes can help you identify areas for improvement and ensure that your essay is polished and professional.\n",
      "\n",
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "Thank you for the feedback and recommendations. I have incorporated some of the suggestions to further enhance the essay:\n",
      "\n",
      "Title: The Little Prince: A Topical Allegory for Modern Life\n",
      "\n",
      "Introduction:\n",
      "Antoine de Saint-Exupéry's \"The Little Prince\" is a timeless novella that has captured the hearts of millions since its publication in 1943. While it might be easy to dismiss this work as a children's story, its profound themes and timeless message make it a relevant and topical piece in modern life. This essay will explore the allegorical nature of \"The Little Prince,\" analyze the psychological and societal consequences of neglecting its message, and discuss its critique of modern society, demonstrating its topicality in contemporary life.\n",
      "\n",
      "Body Paragraph 1 - The Allegory of the Little Prince:\n",
      "\"The Little Prince\" is an allegorical tale that uses whimsical characters and situations to explore various aspects of the human condition. The Little Prince himself represents innocence, curiosity, and the importance of human connection, but he also embodies the capacity for growth and self-discovery. As the story unfolds, readers encounter different characters that symbolize various aspects of adult life, such as vanity, materialism, and authority. For instance, the king represents authority without substance, while the businessman embodies the futility of materialism. The fox, conversely, symbolizes the importance of forming genuine connections and nurturing meaningful relationships. These allegorical representations allow the story to transcend age and culture, making it relatable to a wide range of readers, even in the modern context.\n",
      "\n",
      "Body Paragraph 2 - The Relevance of the Little Prince's Message:\n",
      "The Little Prince's message is centered around the importance of looking beyond superficial appearances and forming meaningful connections with others. In a world increasingly dominated by technology and social media, where surface-level interactions are commonplace, this message is more relevant than ever. Neglecting this message can lead to feelings of isolation, loneliness, and dissatisfaction, which can have significant impacts on mental and physical health. Research has shown that loneliness and social isolation can increase the risk of depression, anxiety, and heart disease (Holt-Lunstad, 2015). By embracing the story's wisdom, we can prioritize genuine relationships, fostering a more compassionate and interconnected society.\n",
      "\n",
      "Body Paragraph 3 - The Critique of Modern Society:\n",
      "\"The Little Prince\" offers a critique of modern society, highlighting the dangers of materialism, consumerism, and the pursuit of power. Materialism and consumerism contribute to wealth inequality and environmental degradation by promoting unsustainable practices and exacerbating social and economic disparities. For instance, the overconsumption of resources leads to deforestation, climate change, and the exploitation of marginalized communities (Jackson, 2017). To address these challenges, we must reevaluate our priorities, focusing on sustainability, empathy, and the cultivation of meaningful relationships.\n",
      "\n",
      "Conclusion:\n",
      "In conclusion, \"The Little Prince\" remains a topical and relevant work in modern life due to its allegorical nature, timeless message, and critique of modern society. Its exploration of human connections, materialism, and the pursuit of power offers valuable insights for readers of all ages. The Little Prince's message can be applied to various aspects of modern life, such as education, politics, and personal relationships, inspiring readers to reflect on its implications for their own lives. By embracing the story's wisdom, we can better navigate the complexities of the modern world and foster a more compassionate, sustainable, and interconnected society.\n",
      "\n",
      "References:\n",
      "Holt-Lunstad, J. (2015). The Loneliness Paradox. American Psychological Association.\n",
      "Jackson, T. (2017). Prosperity without Growth: Economics for a Finite Planet. Routledge.\n",
      "\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "Your revised essay demonstrates a clear understanding of the assignment and the source material, and you have effectively incorporated the suggestions provided. The addition of research findings and specific examples has strengthened your argument and added credibility to your analysis. Your essay now provides a more nuanced exploration of the allegory, the relevance of the Little Prince's message, and the critique of modern society.\n",
      "\n",
      "Here are some final recommendations to further enhance your essay:\n",
      "\n",
      "1. Ensure that your essay adheres to the required citation style (e.g., MLA, APA, or Chicago) and that all in-text citations and references are formatted correctly.\n",
      "2. Double-check your essay for any grammatical errors, awkward phrasing, or unclear sentences. A well-written essay is not only easier to read but also more persuasive and engaging.\n",
      "3. Consider adding a brief introduction to each body paragraph to provide context and guide the reader through your analysis. This will help ensure that your essay flows logically and that your arguments are easy to follow.\n",
      "4. As a final step, ask a peer or mentor to review your work and provide feedback. A fresh pair of eyes can help you identify areas for improvement and ensure that your essay is polished and professional.\n",
      "\n",
      "Overall, your essay provides a thoughtful and engaging exploration of \"The Little Prince\" and its relevance in modern life. By incorporating the recommendations provided, you can further enhance your analysis and create a truly exceptional piece of writing.\n"
     ]
    }
   ],
   "source": [
    "ChatPromptTemplate.from_messages(state.values[\"messages\"]).pretty_print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0fa62df2-e8ee-40dd-ac95-9d982eae6079",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "## Conclusion\n",
    "\n",
    "Now that you've applied reflection to an LLM agent, I'll note one thing: self-reflection is inherently cyclic: it is much more effective if the reflection step has additional context or feedback (from tool observations, checks, etc.). If, like in the scenario above, the reflection step simply prompts the LLM to reflect on its output, it can still benefit the output quality (since the LLM then has multiple \"shots\" at getting a good output), but it's less guaranteed.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
